/** 用于抹平浏览器和钉钉之间的差异 @author dongls */
import {
  getRootWindow
} from '../util/dom';
import dingtalk from '@src/util/dingtalk';
import BaseGallery from '@src/component/common/BaseGallery'
/* utils */
import { isEmpty } from '@src/util/type'
import Log from '@src/util/log.ts'
import { conversionLink } from '@src/util/linkSwitch';
import { checkAuthIsOpenTab } from '@src/util/authTab'

import {
  alert,
  confirm,
  notification,
  notificationSuccess,
  notificationError,
  toast
} from './message';

/** 
 * @description 在新的窗口打开链接，链接必须是全路径 
 * @param {String} url - 链接
 * @param {Boolean} isNeedConvert - 是否需要转换链接
*/
function openLink(url, isNeedConvert = true) {
  
  if (isNeedConvert) {
    url = conversionLink(url);
  }
  
  if (!dingtalk.inDingTalk) {
    return window.open(url)
  }
  
  return dingtalk.biz.openLink(url);
}

/** 
 * 打开一个的tab，如果已经存在则跳转至对应的tab 
 * 
 * tab的id属性按以下格式命名：`[module]_[page](_${key})*`  
 * 示例：customer_view_0fe58f8b-b698-4fc0-9ddb-8ca155452e9
 * 
 * @param {Object} options - tab对应的options，一般包含以下属性{id,title,close,url,fromId}
 * @param {string} options.id - id
 * @param {string} options.title - title
 * @param {boolean} options.close - 是否允许关闭tab
 * @param {string} options.url - tab对应的url
 * @param {string} options.fromId - 打开该tab的源tab的id
 */
export function openTab(options) {
  
  const isHaveAuth = checkAuthIsOpenTab(options)
  
  if (!isHaveAuth) {
    return false
  }
  if(window === window.top && !window._init){
    window.location.href = options.url
  }
  
  let win = getRootWindow(window);
  let origin = window.location.origin;
  
  let message = {
    action: 'shb.system.openFrameTab',
    data: options
  };
  
  win.postMessage(message, origin)
}

/** 根据tab刷新tab */
function refreshTab(id) {
  if (isEmpty(id)) {
    return Log.warn('Caused: refreshTab function paramer id isEmpty', refreshTab.name)
  }
  
  let win = getRootWindow(window);
  let origin = window.location.origin;
  
  let message = {
    action: 'shb.system.realodFrameById',
    data: id
  };
  
  try {
    win.postMessage(message)
  } catch (error) {
    console.error(error)
    try {
      win.postMessage(message, origin)
    } catch (error) {
      console.error(error)
    }
  }
}

/** 根据id, 关闭tab */
export function closeTab(id) {
  let win = getRootWindow(window);
  let origin = window.location.origin;

  let message = {
    action: 'shb.system.closeFrameById',
    data: id
  };

  win.postMessage(message, origin)
}

export function closeCurrentTab() {
  const id = window?.frameElement?.dataset?.id;
  closeTab(id);
}

/**
 * @des 新的页面记录跳转返回上一页
 * @param {string} id 
 */
export function backToFromTab(id) {
  let win = getRootWindow(window);
  let origin = window.location.origin;

  let message = {
    action: 'shb.system.backToFromTab',
    data: id
  };

  win.postMessage(message, origin)
}

function setTabLoadingStatus(options) {
  let win = getRootWindow(window);
  let origin = window.location.origin;
  let message = {
    action: 'shb.system.setFrameLoadingStatus',
    data: options
  }

  win.postMessage(message, origin)
}

function setTabTitle(options) {
  let win = getRootWindow(window);
  let origin = window.location.origin;
  let message = {
    action: 'shb.system.setTabTitle',
    data: options
  }
  
  try {
    win.postMessage(message)
  } catch (error) {
    console.error(error)
    try {
      win.postMessage(message, origin)
    } catch (error) {
      console.error(error)
    }
  }
}
/**
 * @description: 根据id, 打开tab
 * @param {*} id 需要打开tab的id
 */
function goOpenTab(id) {
  let win = getRootWindow(window);
  let origin = window.location.origin;

  let message = {
    action: 'shb.system.openFrameById',
    data: id
  };

  win.postMessage(message, origin)
}

function dataTelevision(options) {
  let win = getRootWindow(window);
  let message = {
    action: 'shb.system.dataTelevision',
    data: {
      name: 'lj'
    }
  }
  
  win.postMessage(message)
}

/**
 * 图片预览
 *
 * @param {*} imageDom - img dom
 * @param {*} imgUrl - 图片链接
 */
function imagePreview({ imageDom, urls, currIndex = 0 }) {
  return BaseGallery.preview(imageDom, currIndex, urls.length > 1);
}

/**
 * 发起内部协同聊天
 * @param {data} old 老版发起内部协同聊天(单聊):比如人员卡片发起聊天，参数 {userId,url} userId:单人员的userId url:当前页面的路径(比如工单详情，事件详情)用来判断是否发送业务消息卡片
 * @param {data} 
 * new 新版发起内部协同聊天(单聊，群聊) {url,memberUserIdList,groupName,bizType,bizId} 
 * memberUserIdList:人员的userId列表 url:当前页面的路径(比如工单详情，事件详情)用来判断是否发送业务消息卡片
 */
function open_insideIM(data) {
  let win = getRootWindow(window);
  if (data) {
    sessionStorage.setItem('inside_bizInfo', JSON.stringify(data));
    if (Array.isArray(data.memberUserIdList)) {
      if (data.bizType) {
        win?.startChat({
          memberUserIdList: data.memberUserIdList,
          groupName: data.groupName,
          bizType: data.bizType,
          bizId: data.bizId,
        });
      } else {
        // 不带业务
        if (data.tagIdList) {
          win?.startChat({
            memberUserIdList: data.memberUserIdList,
            tagIdList: data.tagIdList,
          })
          return;
        }
        win?.startChat({
          memberUserIdList: data.memberUserIdList,
        });
      }
    } else {
      win?.startChat({
        // 兼容老版本只能发起单聊
        memberUserIdList: [data.userId],
      });
    }
  }
}

export const platform = {
  inDingTalk: dingtalk.inDingTalk,
  
  alert,
  confirm,
  notification,
  notificationSuccess,
  notificationError,
  toast,
  
  openTab,
  refreshTab,
  closeTab,
  setTabLoadingStatus,
  
  openLink,
  imagePreview,
  
  setTabTitle,
  goOpenTab,
  dataTelevision,
  open_insideIM,
};

export default platform;